package com.ruigi.control;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruigi.common.Basecontext;
import com.ruigi.pojo.AddressBook;
import com.ruigi.pojo.R;
import com.ruigi.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class Addresscontrol {
    @Autowired
    private AddressService addressService;

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook, HttpSession session) {

        System.out.println("123");
        addressBook.setUserId(Basecontext.getid());
        addressService.save(addressBook);
        return R.success("addressBook");


    }

    @GetMapping("/list")
    public R<List> findAddressList(AddressBook addressBook) {
        addressBook.setUserId(Basecontext.getid());
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        return R.success(addressService.list(queryWrapper));


    }

    @PutMapping("/default")
    public R<AddressBook> setdefault(@RequestBody AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, Basecontext.getid());
        queryWrapper.set(AddressBook::getIsDefault, 0);
        addressService.update(queryWrapper);
        addressBook.setIsDefault(1);
        addressService.updateById(addressBook);
        return R.success(addressBook);
    }

    @GetMapping("/default")
    public R<AddressBook> getdefulet() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, Basecontext.getid());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressService.getOne(queryWrapper);
        return R.success(one);

    }
}
